class ListNode {
    constructor() {
        this.length = new WeakMap() //静态方法 需要编译
        this.head = new WeakMap() //静态方法 需要编译
        this.length.set(this, 0)
        this.head.set(this, null)
    }
    //向链表尾部添加一个新的元素
    append(data) {
        let node = new Node(data)
        let current = this.getHead()
        if (current == null) {
            this.head.set(this, node)
        } else {
            while (current.next) {
                current = current.next
            }
            current.next = node
        }
        let l = this.size()
        l++
        this.length.set(this, l)
    }
    //向链表特定位置插入元素
    insert(position, data) {
        if (position >= 0 && position <= this.size()) {
            let node = new Node(data)
            let current = this.head.get(this)
            if (position === 0) {
                node.next = current
                this.head.set(this, node)
            } else {
                let index = 0
                let previous
                while (index < position) {
                    current = current.next
                    previous = current
                    index++
                }
                node.next = current
                previous.next = node
            }
            let l = this.size()
            l++
            this.length.set(this, l)
            return true
        }
        return false
    }
    isEmpty() {
        return this.size() === 0
    }
    getHead() {
        return this.head.get(this)
    }

    size() {
        return this.length.get(this)
    }
    // 返回链表中某元素的索引，如果没有返回-1
    indexOf(node) {
        let current = this.head.get(this)
        let index = 0
        if (current === node) {
            return index
        }
        while (current !== node && index < this.size()) {
            current = current.next
            index++
        }
        return current && current === node ? index : -1
    }
    //从链表移除一项
    remove(node) {
        let index = this.indexOf(node)
        return this.removeAt(index)
    }
    //返回链表中某元素的索引，如果没有返回-1
    removeAt(position) {
        if (position < 0 || position > length.size) {
            return null
        }
        let current = this.head.get(this)
        let index = -1
        let previous
        while (index < position) {
            current = current.next
            previous = current
            index++
        }
        previous.next = current.next
        let l = this.size()
        l--
        this.length.set(this, l)
        return current
    }

}